<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" href="../lib/layui-v2.1.6/layui/css/layui.css">
<link rel="stylesheet" href="../resources/css/importBill.css">
<body>
	<div id="main">
		<div id="top">
			<table>
				<tr>
					<td><i id="clinicName" class="color1"></i></td>
					<td class="layui-form section"><label class="layui-form-label color1">科室:</label>
						<div class="layui-input-block" style="width:150px">
							<select id="department" name="department">
							</select>
						</div></td>
					<td><label class="layui-form-label color1">日期:</label>
						<div class="layui-input-block" style="width:150px">
							<input id="dateTime" class="layui-input" type="text" readonly>
						</div></td>
					<td>
						<i class="layui-icon icon" id="add" style="color:#fff">&#xe61f;</i>
					</td>
				</tr>
			</table>
		</div>
		<div id="middle">
			<table class="layui-table" lay-skin="line row" id="importBillTable" lay-filter="tableListen" lay-even>
			</table>
		</div>
		<div id="bottom">
			<table>
				<tr class="color1">
					<td>总支出：<input type="text" name="paySum" class="inputCss" disabled="disabled"></td>
					<td>总收入：<input type="text" name="incomeSum" class="inputCss" disabled="disabled"></td>
					<td>合计：<input type="text" name="Sum" class="inputCss" disabled="disabled"></td>
					<td><button id="importBillSubmit" class="layui-btn" style="background:transparent">保存并新增</button></td>
				</tr>
			</table>
		</div>
		<input type="hidden" id="iframeWidth" value=""> <input type="hidden" id="iframeHeight" value="">
	</div>
</body>
<script type="text/javascript" src="../lib/jquery.min.js"></script>
<script type="text/javascript" src="../lib/layui-v2.1.6/layui/layui.js"></script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>
</script>
<script>
	var importBillData = new Array();//表格数据
	layui.use([ 'table', 'laydate','form' ], function() {
		var $ = layui.jquery;
		var form = layui.form;
		var table = layui.table; //调用layui插件里的表格模块
		var laydate = layui.laydate; //调用Layui插件里的时间组件
		var layer = layui.layer; //调用layui插件里的弹出层
		initFrame();//初始化界面
		renderTable(importBillData);//初始化和更新table
		resize(); //屏幕自适应
		listen(); //监听事件
		
		//初始化界面
		function initFrame() {
			var loginUser = JSON.parse(localStorage.getItem("loginUser"));
			initDate(); //初始化日期
			initDepartmentSelect(loginUser);//初始化科室下拉栏和医生下拉栏
			$("#clinicName").html(loginUser.clinicName);//初始化门诊名
			$("#clinicName").attr("data-id",loginUser.clinicId);//初始化门诊名
		}
		
		
		function resize() {
			//屏幕自适应
			$(window).resize(function() {
				renderTable(importBillData);
			});
		}
		
		function listen() {
			$('#add').click(
					function() { //顶部添加项按钮监听
						//importBill_operator : 1:新增；2：编辑
						localStorage.setItem("importBill_operator",1);
						layer.open({ //弹出新增框
							title : "新增",
							type : 2,
							area : ["508px", "540px"],
							content : "../views/billManager/addFundBillProject.html",
							btn : [ "新增", "取消"],
							btn1 : function(layero, index) { //点击弹出框新增按钮触发事件
								var iframeWin = window[index.find('iframe')[0]['name']]; //获取弹出框对象
								var isSuccess = iframeWin.importFundSubmit(); //调用弹出框的submit函数
								if (isSuccess == 200) {
									importBillData.push(JSON.parse(localStorage
											.getItem("importBillIframeData"))); //获取弹出框数据放入全局数组importBillData
									localStorage.removeItem("importBillIfraneData");
									renderTable(importBillData); //更新表格
									layer.msg("添加成功");
								}
							},
							btn2 : function(layero, index) { //点击弹出框取消按钮触发事件
							},
						});
					});
			
			table.on('tool(tableListen)', function(obj) { //编辑、删除按钮监听
				var data = obj.data; //获取当前行的数据
				var layEvent = obj.event; //获取layEvent对应的值
				var tr = obj.tr; //获取当前tr的DOM对象
				if (layEvent == 'edit') { //点击编辑时
					//importBill_operator : 1:新增；2：编辑
					localStorage.setItem("importBill_operator",2);
					localStorage.setItem("editTableData", JSON.stringify(data));//传值localStorage到编辑框
					layer.open({ //弹出编辑框
						title : "编辑",
						type : 2,
						area : ["508px","540px"],
						content : "../views/billManager/addFundBillProject.html",
						cancel : function(index, layero) {
							localStorage.removeItem("editTableData"); //关闭编辑框时消除传值的localStorage
						},
						btn : [ "更改", "取消" ],
						btn1 : function(layero, index) {
							var iframeWin = window[index.find('iframe')[0]['name']];
							iframeWin.importFundSubmit();
							//获取更新数据
							var update = JSON.parse(localStorage.getItem("importBillIframeData"));
							localStorage.removeItem("importBillIframeData"); //关闭编辑框时消除传值的localStorage
							//重置窗口数据
							importBillData.splice(tr.index(), 1,update);
							renderTable(importBillData);
							layer.msg("更改成功");
							
							layer.close(layero);
						},
						btn2 : function(layero, index) { //点击弹出框取消按钮触发事件
						},
					});
					localStorage.removeItem("importBillIframeData"); //关闭编辑框时消除传值的localStorage
				} else if (layEvent == 'del') {
					layer.confirm('确定删除吗？', function(index) {
						importBillData.splice(tr.index(), 1);
						obj.del(); //删除对应行(tr)的DOM结构，并更新缓存
						layer.close(index); //向服务器端发送删除指令
						renderTable(importBillData);
					});
				}
			});

			$('#importBillSubmit').click(function() {
				if(importBillData == null || importBillData.length == 0) {
					layer.msg("请填写必要信息");
					return;
				}
				var submitData = {
					"clinicId" : $("#clinicName").attr("data-id"),
					"departmentId" : $("#department").val(),
					"sum" : $("input[name='Sum']").val(),
					"incomeSum" : $("input[name='incomeSum']").val(),
					"paySum" : $("input[name='paySum']").val(),
					"submitTime" : $("#dateTime").val(),
					"projects" : JSON.stringify(importBillData),
					"clientId" : 0,
					"status" : 0,
				};
				console.log("importBillSubmit.submitData");
				console.log(submitData);
				$.ajax({
					type : "post",
					data : submitData,
					url : "../billController/addFundBill",
					success : function(response) {
						if(response.code != 200) {
							console.error(response);
							return;
						}
						console.log("addTreatmentBill.response");
						console.log(response);
						layer.msg("添加成功");
						importBillData = [];
						renderTable(importBillData);
					}
				});

			});
			 
			$('.icon').mouseenter(function() {
				$('.icon').css({
					'color' : '#c2c2c2'
				});
			});
			$('.icon').mouseleave(function() {
				$('.icon').css({
					'color' : '#fff'
				});
			});
		}
		
		function initDepartmentSelect(loginUser) {
			var param = {
				clinicId : loginUser.clinicId,
			};
			$.ajax({
				type : "post",
				url : "/Hospital/clinicController/getClinicAllDepartment",
				data : param,
				success : function(response) {
					if (response.code != 200) {
						console.error(response);
						return;
					}
					//console.log("importTreatBill.getClinicAllDepartment");
					//console.log(response);
					var result = response.result;
					for (var i = 0; i < result.length; i++) {
						var departmentId = result[i].departmentId;
						var departmentName = result[i].departmentName;
						var name = result[i].name;
						$("#department").append(
								"<option value="+departmentId+">" + departmentName + "</option>");
					}
					//重绘
					form.render();
				}
			});
		}
		
		function initDate() {
			var nowdate = new Date(); //获取当前时间
			var nowYear = nowdate.getFullYear() + "-" + (nowdate.getMonth() + 1) + "-"
					+ nowdate.getDate();//获取当前年份
			var max = nowdate.getFullYear() + "-" + (nowdate.getMonth() + 1) + "-"
					+ nowdate.getDate();
			var min = nowdate.getFullYear() + "-" + (nowdate.getMonth() + 1) + "-01";
			laydate.render({ //执行一个laydate实例
				elem : '#dateTime', //指定元素
				theme : "#55565b",
				value : nowYear,
				max : max,
				min : min
			});
		}
		
		function renderTable(tableData) {
			//console.log("renderTable.tableData");
			//console.log(tableData);
			var rightFixed = $(document.body).width() * 0.13;
			var costTypeWidth = $(document.body).width() * 0.1;
			var tableWidth = $(document.body).width() * 0.223;
			var tableHeight = $(document.body).height() * 0.799;
			var iconSize = $(document.body).width() * 0.02;
			$('.icon').css({
				'font-size' : iconSize
			});
			table.render({
				elem : '#importBillTable',
				center : true,
				height : tableHeight,
				cols : [ [ {
					field : 'extraInfo',
					width : tableWidth,
					title : '摘要',
					align : 'center'
				}, {
					field : 'projectName',
					width : tableWidth,
					title : '项目名称',
					align : 'center'
				}, {
					field : 'type',
					width : costTypeWidth,
					title : '费用类型',
					align : 'center'
				}, {
					field : 'cost',
					width : tableWidth,
					title : '金额',
					align : 'center'
				}, {
					fixed : 'right',
					width : rightFixed,
					align : 'center',
					toolbar : '#barDemo'
				} ] ],
				data : tableData
			});
			//费用合计
			var incomeSum = 0;
			var paySum = 0;
			var sum = 0;
			for (var i = 0; i < tableData.length; i++) {
				if (tableData[i].type == "收入") {
					incomeSum += parseFloat(tableData[i].cost);
				} else if (tableData[i].type == "支出") {
					paySum += parseFloat(tableData[i].cost);
				}
				sum = incomeSum - paySum;
			}
			$('input[name="paySum"]').val(paySum);
			$('input[name="incomeSum"]').val(incomeSum);
			$('input[name="Sum"]').val(sum);
		}
		
	});
</script>
</html>